package com.zdy.im.tio.command.handler;


import com.alibaba.fastjson.JSONObject;
import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.util.json.JsonUtils;
import com.zdy.im.chat.ChatMessageEnum;
import com.zdy.im.chat.ChatMessageInfo;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.core.ICommand;
import com.zdy.im.enums.ImMessageTypeEnum;
import com.zdy.im.tio.TioServerConfig;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;
import com.zdy.im.tio.command.ProtocolManager;
import com.zdy.im.tio.packets.ChatReadStatusRequestVo;
import com.zdy.im.user.dto.request.ImChatReadStatusRequestDto;
import com.zdy.im.user.dto.request.ImMessageReadRequestDto;
import com.zdy.im.user.dto.response.ImMessageReadResponseDto;
import com.zdy.im.user.service.ImMessageReadService;
import com.zdy.im.user.service.ImRoomChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;


/**
 * 版本: [1.0]
 * 功能说明: 聊天请求cmd消息命令处理器
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档",group = "SOCKET-GROUP")
public class RoomReadStatusRequestHandler extends AbstractCommandHandler {

	@Autowired
	private ImRoomChatMessageService imRoomChatMessageService;

	@Autowired
	private ImMessageReadService imMessageReadService;

	@Override
	public ICommand command() {
		return Command.COMMAND_CHAT_GROUP_STATUS_REQ;
	}

	public ICommand responseCmd() {
		return Command.COMMAND_CHAT_GROUP_STATUS_RESP;
	}

	@ApiDoc(
			cmd = "107",methodType = "ws",
			value = "读群里消息,撤销,删除消息协议,协议码cmd=107",
			request = ChatReadStatusRequestVo.class,
			response = ImChatReadStatusRequestDto.class
	)
	@Override
	public Packet handler(Packet wsPacket, ChannelContext channelContext) throws ImException {
		WsRequest packet = (WsRequest) wsPacket;
		if (packet.getBody() == null) {
			throw new ImException("body is null");
		}
		ChatMessageInfo sendInfo = JsonUtils.parseObject(packet.getWsBodyText(), ChatMessageInfo.class);
		//聊天数据格式不正确
		ChatMessageEnum chatMessageEnum = ChatMessageEnum.getEnum(sendInfo.getType());
		if (sendInfo == null || chatMessageEnum == null) {
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
			return respChatPacket;
		}
		JSONObject ext = sendInfo.getExt();
		if (ext == null) {
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
			return respChatPacket;
		}
		ChatReadStatusRequestVo vo = JsonUtils.parseJson(ext, ChatReadStatusRequestVo.class);
		if (vo == null) {
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
			return respChatPacket;
		}
		String toUserId = String.valueOf(vo.getToUserId());

		boolean result = false;

		WsResponse wsResponse = null;
		if(chatMessageEnum.getDbValue() == ChatMessageEnum.MESSAGE_STATUS_UNREAD.getDbValue()){
			ImMessageReadRequestDto imMessageRead = ImMessageReadRequestDto.build();
			imMessageRead.setUserId(vo.getToUserId());
			imMessageRead.setMessageId(vo.getSendUserId());
			imMessageRead.setType(ImMessageTypeEnum.Group.getKey());
			imMessageRead.setGlobalId(vo.getGlobalId());
			result = saveAndUpdateMessageRead(imMessageRead);
			if (!result) {
				return ProtocolManager.ResponsePacket.dataToSendFailed(channelContext);
			}
			imMessageRead.setType(ImMessageTypeEnum.ROOM_READ.getKey());
			wsResponse = WsResponse.fromText(JsonUtils.toJson(imMessageRead), TioServerConfig.CHARSET);
		}else{
			ImChatReadStatusRequestDto chatRequestDto = ImChatReadStatusRequestDto.build().clone(vo);
			chatRequestDto.setReadType(chatMessageEnum.getDbValue());
			chatRequestDto.setCmd(sendInfo.getCmd());
			result = imRoomChatMessageService.updateImChatMessageReadStatus(chatRequestDto);
			if (!result) {
				return ProtocolManager.ResponsePacket.dataToSendFailed(channelContext);
			}
			wsResponse = WsResponse.fromText(JsonUtils.toJson(chatRequestDto), TioServerConfig.CHARSET);
		}

		Tio.sendToUser(channelContext.tioConfig, toUserId, wsResponse);
		return ProtocolManager.ResponsePacket.success(channelContext,responseCmd());

	}

	private boolean saveAndUpdateMessageRead(ImMessageReadRequestDto imMessageRead) {
		ImMessageReadResponseDto dto = imMessageReadService.getImMessageReadByUser(imMessageRead);
		if(dto == null){
			imMessageReadService.saveImMessageRead(imMessageRead);
		}else{
			dto.setGlobalId(imMessageRead.getGlobalId());
			imMessageReadService.updateImMessageRead(imMessageRead);
		}
		return true;
	}

}
